package com.ifdom.lock;

import java.util.concurrent.locks.Lock;

/**
 * 同一时刻只有两个线程能够获取到锁，这表明TwinsLock可以按照预期正确工作
 *
 * @Author ifredomvip@gmail.com
 * @Date 2022/10/1 18:17
 */
public class TwinsLockTest {
    public static void main(String[] args) throws InterruptedException {
        final Lock lock = new TwinsLock();
        class Worker extends Thread {
            Worker(String name) {
                super(name);
            }

            @Override
            public void run() {
                while (true) {
                    lock.lock();
                    try {
                        Thread.sleep(1000);
                        System.out.println(Thread.currentThread().getName());
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        System.out.println("InterruptedException中断");
                        e.printStackTrace();
                    } finally {
                        lock.unlock();
                    }
                }
            }

        }

        //启动10个线程
        for (int i = 0; i < 10; i++) {
            Worker w = new Worker("线程" + i);
            w.setDaemon(true);
            w.start();
        }

        //每隔1秒换行
        for (int i = 0; i < 10; i++) {

            Thread.sleep(1000);
            System.out.println();
        }
    }


}
